package com.ljl.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ljl.basic.exception.BusinessException;
import com.ljl.basic.jwt.JwtUtils;
import com.ljl.basic.jwt.LoginData;
import com.ljl.basic.jwt.RsaUtils;
import com.ljl.basic.util.AjaxResult;
import com.ljl.basic.util.HttpUtil;
import com.ljl.basic.util.MD5Utils;
import com.ljl.basic.util.StrUtils;
import com.ljl.system.domain.Menu;
import com.ljl.user.constant.WxConstants;
import com.ljl.user.domain.Logininfo;
import com.ljl.user.domain.User;
import com.ljl.user.domain.Wxuser;
import com.ljl.user.dto.BinderDto;
import com.ljl.user.dto.LoginDto;
import com.ljl.user.mapper.LogininfoMapper;
import com.ljl.user.mapper.UserMapper;
import com.ljl.user.mapper.WxuserMapper;
import com.ljl.user.service.ILogininfoService;
import com.ljl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer accountType = loginDto.getAccountType();
        // 校验空值
        if(StringUtils.isEmpty(account) && StringUtils.isEmpty(password) &&StringUtils.isEmpty(accountType)){
            throw new BusinessException("请输入用户名或密码");
        }
        // 查询用户名正确
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("用户名或密码错误！");
        }
        // 比对密码是否正确
        String salt = logininfo.getSalt();
        String md5Input = MD5Utils.encrypByMd5(password + salt);
        String LogininfoPassword = logininfo.getPassword();
        if(!md5Input.equals(LogininfoPassword)){
            throw new BusinessException("用户名或密码错误！");
        }
//        String dbMd5Pwd = logininfo.getPassword();
//        String md5Pwd = MD5Utils.encrypByMd5(password + logininfo.getSalt());
//        if(!dbMd5Pwd.equals(md5Pwd)){
//            throw new BusinessException("用户名或密码错误!!!");
//        }
        // 判断状态
        if (!logininfo.getDisable()){
            throw new BusinessException("你的账户已经被冻结，请联系管理员！！");
        }
        // 设置
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        Map<String, Object> map = new HashMap<>();
//
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//
//        map.put("token",token);
//        map.put("logininfo", logininfo);

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(map);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();

        try {
            if (logininfo.getType() == 0){
                List<String> permissions = logininfoMapper.findPermissionByLogininfoId(logininfo.getId());
                List<Menu> menus = logininfoMapper.findMenuByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);

                map.put("permissions",permissions);
                map.put("menus",menus);

            }

            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300000);
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public AjaxResult wechatLogin(String code) {

        String url = WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);

        String jsonStr = HttpUtil.httpGet(url);

        // 将json格式的字符串转换成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        Wxuser wxuser = wxuserMapper.findByOpenid(openid);

        if (wxuser != null && wxuser.getUser_id() != null){
            Logininfo logininfo = logininfoMapper.findLogininfoByUserId(wxuser.getUser_id());
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(map);

        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid", openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }
    }

    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String accessToken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode) ){
            throw new BusinessException("请输入电话或验证码");
        }

        Object redisCode = redisTemplate.opsForValue().get("binder:" + phone);

        if(redisCode == null){
            throw new BusinessException("验证码过期请重新获取");
        }

        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码输入错误请重新输入");
        }
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        System.out.println(url);
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = url2Wxuser(jsonStr);
        User user = userMapper.findByPhone(phone);

        if (user== null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);

            wxuser.setUser_id(user.getId());
        } else {
            throw new BusinessException("此号码已经注册");
        }
        wxuserMapper.save(wxuser);

        Logininfo logininfo = logininfoMapper.findLogininfoByUserId(wxuser.getUser_id());
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(map);

    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String randomPwd = StrUtils.getRandomString(8);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser url2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") +
                jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

}
